<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>编辑页面</title>
<script type="text/javascript" src="js/jquery-1.12.4.js"></script>
<script type="text/javascript" src="js/jquery.params.js"></script>

<script type="text/javascript">
var id =0;

$(function(){
	getGrade();
	//console.log($.query.get("id"))
	$("#addbtn").hide()
	$("#updatebtn").hide()
	if($.query.get("id")){
		id = $.query.get("id");
		console.log(id)
		//异步加载学生信息
		$.getJSON("stu/fetch",{"id":id},function(res){
			 console.log(res.data)
			 $("#name").val(res.data.name);
			 $("#age").val(res.data.age);
			 $("#gid").val(res.data.gid);
		})
		$("#updatebtn").show();
	}else{
		$("#addbtn").show();
		
	}
})

function getGrade(){
	$.getJSON("grade/all",function(res){
		//console.log(res)
		var array = res.data;
		for(var i in array){
			//console.log(array[i])
			$("#gid").append(`
					<option value="${array[i].id}">
					${array[i].gradename}
					</option>`)
		}
	})
}

 function add(){
	 var name = $("#name").val();
	 var age = $("#age").val();
	 var gid = $("#gid").val();
	 var data = {
		 "name":name,
		 "age":age,
		 "gid":gid
	 }
	 console.log(data)
	 $.post("stu/add",data,function(res){
		 console.log(res)
		 if(res.resultCode==200){
			 	alert("添加成功")
			}else{
				alert("添加失败"+res.message)
			}
	 })
} 
 
 function update(){
	 var name = $("#name").val();
	 var age = $("#age").val();
	 var gid = $("#gid").val();
	 var data = {
		 "id":id,
		 "name":name,
		 "age":age,
		 "gid":gid
	 }
	 console.log(data)
	 $.post("stu/update",data,function(res){
		 console.log(res)
		 if(res.resultCode==200){
			 	alert("更新成功")
			}else{
				alert("更新失败"+res.message)
			}
	 })
} 
</script>
</head>
<body>
	<h1>编辑学生</h1>
	<a href="index.html">回到主页</a>
	<form>
		<p>姓名:<input type="text" name="name" id="name"/></p>
		<p>年龄:<input type="number" max="80" min="7" name="age" id="age"/></p>
		<p>年级:
			<select name="gid" id="gid"></select>
		</p>
		<p> 
			<input type="hidden" name="id" id="id" value="0"/>
			<input type="button" id="addbtn" onclick="add()" value="新增"/>
			<input type="button" id="updatebtn" onclick="update()" value="更新"/>
		</p>
	</form>
</body>
</html>